using GLib;
using Rob;

namespace Rob
{
	namespace Actions
	{
		public class RunCommand: Rob.Actions.Action
		{
			private string _start_cmd;
			private string _end_cmd;
			public string start_cmd
			{
				set{_start_cmd = value;}
				get{return _start_cmd;}
			}
			public string end_cmd
			{
				get{ return _end_cmd;}
				set{ _end_cmd = value; }

			}
			public override bool load( KeyFile kf, string name)
			{
				try
				{
					base.load(kf, name);
					_end_cmd = kf.get_string(name, "end_cmd");
					_start_cmd = kf.get_string(name, "start_cmd");

					_title = kf.get_string(name, "title");
				}
				catch (GLib.KeyFileError e)
				{
					GLib.critical("Can't load %s config: %s", name, e.message);
					return false;
				}
				_name = name;
				return true;
			}
			public override bool save(ref KeyFile kf)
			{
				try
				{
					base.save(ref kf);
					kf.set_string(name,"end_cmd",_end_cmd);
					kf.set_string(name,"start_cmd",_start_cmd);
					kf.set_string(name,"title",title);
				}
				catch( GLib.KeyFileError e)
				{
					GLib.critical("Can't save %s : %s\n",name, e.message);
					return false;
				}
				return true;
			}
			construct 
			{

			}
			public override void run()
			{
				if( this._start_cmd != "")
				{
					try
					{
						GLib.Process.spawn_command_line_async(this._start_cmd);
					}
					catch ( GLib.SpawnError e )
					{
						GLib.critical("%s failed to start: %s\n", this._start_cmd, e.message);
					}
				}
			}
			public override void stop()
			{
				if(this._end_cmd != "")
				{
					try
					{
						GLib.Process.spawn_command_line_async(this._end_cmd);
					}
					catch ( GLib.SpawnError e)
					{
						GLib.critical("%s failed to stop: %s\n", this._end_cmd, e.message);
					}
				}
			}


			[ModuleInit]
			public Type register_rb_plugin (TypeModule module) 
			{
				stdout.printf ("Registering plugin %s\n", "RunCommand");
				return typeof (RunCommand);
			}
		}
	}
}
